//
//  NSString+Utils.m
//  KKMYForU
//
//  Created by 黄磊 on 13-10-31.
//  Copyright (c) 2013年 黄磊. All rights reserved.
//

#import "NSString+Utils.h"

#define ONE_DATE_TIME (24 * 60 * 60)

#define TWO_DATE_TIME (2 * ONE_DATE_TIME)

#define THREE_DATE_TIME (3 * ONE_DATE_TIME)

#define CUR_TIMEZONE (8 * 60 * 60)

// 基域名
static NSString *s_baseHost = nil;
// 图片服务器
static NSString *s_sourceUrl = nil;

// 本地音频存储路径
static NSString *locDocumentPath = nil;
// 本地音频存储路径
static NSString *locAudioPath = nil;
// 本地图片存储路径
static NSString *locImagePath = nil;
// 本地头像存储路径
static NSString *locAvatarPath = nil;
// 本地临时文件存储路径
static NSString *locTempPath = nil;
//  本地启动页图片
static NSString *launchImagePath = nil;

@implementation NSString (Utils)

+ (NSString *)localizedString:(NSString *)format, ...
{
    NSString *returnStr = NSLocalizedString(format, nil);
    if (returnStr) {
        va_list arguments;
        NSString *eachReplaceStr;
        int index = 0;

        va_start(arguments, format);
        while ((eachReplaceStr = va_arg(arguments, id))) {
            NSString *str = [NSString stringWithFormat:@"{%d}", index];
            returnStr = [returnStr stringByReplacingOccurrencesOfString:str withString:eachReplaceStr];
            index++;
        }
        va_end(arguments);
    }
    return returnStr;
}

+ (NSString *)getBaseHost
{
    if (s_baseHost == nil) {
#if (defined(DEBUG) || INHOUSE)
        BOOL isOn = [[NSUserDefaults standardUserDefaults] boolForKey:@"canSetBaseHost"];
        if (isOn) {
            NSString *aBaseHost = [[NSUserDefaults standardUserDefaults] stringForKey:@"baseHost"];
            if (aBaseHost.length > 0) {
                s_baseHost = aBaseHost;
                if (![s_baseHost hasSuffix:@"http://"]) {
                    s_baseHost = [@"http://" stringByAppendingString:s_baseHost];
                }
            }
        }
#endif
        if (s_baseHost == nil) {
            s_baseHost = kBaseHost;
        }
    }
    return s_baseHost;
}

+ (NSString *)getSourceUrl
{
    if (s_sourceUrl == nil) {
#if (defined(DEBUG) || INHOUSE)
        BOOL isOn = [[NSUserDefaults standardUserDefaults] boolForKey:@"canSetBaseHost"];
        if (isOn) {
            NSString *aBaseHost = [[NSUserDefaults standardUserDefaults] stringForKey:@"sourceUrl"];
            if (aBaseHost.length > 0) {
                s_sourceUrl = aBaseHost;
                if (![s_sourceUrl hasSuffix:@"http://"]) {
                    s_sourceUrl = [@"http://" stringByAppendingString:s_baseHost];
                }
            }
        }
#endif
        if (s_sourceUrl == nil) {
            s_sourceUrl = kSourceUrl;
        }
    }
    return s_sourceUrl;
}

- (BOOL)checkPhoneNum
{
//    if (self.length > 6) {
//        return YES;
//    }
//    return NO;
    //检查所有手机与座机
    NSString *mobile =  @"((\\d{11})|^((\\d{7,8})|(\\d{4}|\\d{3})-(\\d{7,8})|(\\d{4}|\\d{3})-(\\d{7,8})-(\\d{4}|\\d{3}|\\d{2}|\\d{1})|(\\d{7,8})-(\\d{4}|\\d{3}|\\d{2}|\\d{1}))$)";
    NSPredicate *regextestmobile = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", mobile];
    if ([regextestmobile evaluateWithObject:self]) {
        return YES;
    }else{
        return NO;
    }
}

- (BOOL)checkMobileNum
{
    if ([self length] <= 0) {
        return NO;
    }
    if ([self length] != 11) {
        return NO;
    }
    
#ifdef DEVELOPING
    return YES;
#endif
    NSString * MOBILE = @"^1(3[0-9]|5[0-35-9]|8[025-9]|70)\\d{8}$";
    NSString * CM = @"^1(34[0-8]|(3[5-9]|5[017-9]|8[278])\\d)\\d{7}$";
    NSString * CU = @"^1(3[0-2]|5[256]|8[56])\\d{8}$";
    NSString * CT = @"^1((33|53|8[09])[0-9]|349)\\d{7}$";
    // NSString * PHS = @"^0(10|2[0-5789]|\\d{3})\\d{7,8}$";
    NSPredicate *regextestmobile = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", MOBILE];
    NSPredicate *regextestcm = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CM];
    NSPredicate *regextestcu = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CU];
    NSPredicate *regextestct = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CT];
    if (([regextestmobile evaluateWithObject:self] == YES)
        || ([regextestcm evaluateWithObject:self] == YES)
        || ([regextestct evaluateWithObject:self] == YES)
        || ([regextestcu evaluateWithObject:self] == YES))
    {
        return YES;
    }
    else
    {
        return NO;
    }
}

- (BOOL)checkText
{
    return YES;
    NSString *matchStr = @"^[A-Za-z0-9\u4E00-\u9FA5_-]+$";
    NSPredicate *regextest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", matchStr];
    if ([regextest evaluateWithObject:self] == YES) {
        return YES;
    } else {
        return NO;
    }
    
}

+ (BOOL)isContainsEmoji:(NSString *)string
{
    
    __block BOOL isEomji = NO;
    
    [string enumerateSubstringsInRange:NSMakeRange(0, [string length])
                               options:NSStringEnumerationByComposedCharacterSequences
                            usingBlock: ^(NSString *substring, NSRange substringRange, NSRange enclosingRange, BOOL *stop)
     {
         const unichar hs = [substring characterAtIndex:0];
         
         // surrogate pair
         if (0xd800 <= hs && hs <= 0xdbff) {
             if (substring.length > 1) {
                 const unichar ls = [substring characterAtIndex:1];
                 const int uc = ((hs - 0xd800) * 0x400) + (ls - 0xdc00) + 0x10000;
                 if (0x1d000 <= uc && uc <= 0x1f77f) {
                     isEomji = YES;
                 }
             }
         } else if (substring.length > 1) {
             const unichar ls = [substring characterAtIndex:1];
             if (ls == 0x20e3) {
                 isEomji = YES;
             }
         } else {
             // non surrogate
             if (0x2100 <= hs && hs <= 0x27ff && hs != 0x263b) {
                 isEomji = YES;
             } else if (0x2B05 <= hs && hs <= 0x2b07) {
                 isEomji = YES;
             } else if (0x2934 <= hs && hs <= 0x2935) {
                 isEomji = YES;
             } else if (0x3297 <= hs && hs <= 0x3299) {
                 isEomji = YES;
                 
             } else if (hs == 0xa9 || hs == 0xae || hs == 0x303d || hs == 0x3030 || hs == 0x2b55 || hs == 0x2b1c || hs == 0x2b1b || hs == 0x2b50|| hs == 0x231a ) {
                 isEomji = YES;
             }
         }
     }];
    
    return isEomji;
}

// 转换成带星星的电话号
- (NSString *)convertToCoverTel
{
    NSString *telCover = nil;
    if(self.length >= 7)
    {
        telCover = [NSString stringWithFormat:@"%@****%@", [self substringToIndex:3], [self substringFromIndex:7]];
    }
    return telCover;
}

+ (NSString *)getHourWithMinute:(float)minute
{
    if (minute < 60) {
        return @"<1";
    }
    int hour = minute / 60;
    return [NSString stringWithFormat:@"%d", hour];
}

- (float)heightWithFont:(UIFont *)font andWidth:(float)width
{
    float height = 0;
    float theHeight = 0;
    NSArray *array = [self componentsSeparatedByString:@"\n"];
    for (NSString *str in array) {
        if (str == nil || [str isEqualToString:@""] == YES) {
            CGSize size = textSizeWithFont(@"test", font);
            theHeight = size.height;
            height += theHeight;
            continue;
        }
        CGSize size = textSizeWithFont(str, font);
        theHeight = size.height;
        int count = size.width / width;
        height += theHeight * (count + 1);
    }
    height = height - theHeight;
    return height;
}

- (float)calculateHeightWithFont:(UIFont *)font andWidth:(float)width
{
    // 判断是否存在换行符
    NSRange range = [self rangeOfString:@"\n"];
    if (range.location == NSNotFound) { // 不存在
        
        CGSize size = textSizeWithFont(self, font);
        int rowNum = size.width / width;
        return (rowNum+1) * size.height;
        
    }else {                             // 存在
        
        float height = 0;
        float theHeight = 0;
        NSArray *array = [self componentsSeparatedByString:@"\n"];
        for (NSString *str in array) {
            if (str == nil || [str isEqualToString:@""] == YES) {
                CGSize size = textSizeWithFont(@"test", font);
                theHeight = size.height;
                height += theHeight;
                continue;
            }
            CGSize size = textSizeWithFont(str, font);
            theHeight = size.height;
            int count = size.width / width;
            height += theHeight * (count + 1);
        }
        return height;
    
    }
}

- (BOOL)isNewThanVersion:(NSString *)oldVersion
{
    NSArray *arrayNew = [self componentsSeparatedByString:@"."];
    NSArray *arrayOld = [oldVersion componentsSeparatedByString:@"."];
    int len = MIN(arrayNew.count, arrayOld.count);
    for (int i = 0; i < len; i++) {
        if ([[arrayNew objectAtIndex:i] intValue] > [[arrayOld objectAtIndex:i] intValue]) {
            return YES;
        } else if ([[arrayNew objectAtIndex:i] intValue] < [[arrayOld objectAtIndex:i] intValue]) {
            return NO;
        }
    }
    return NO;
}

- (NSString *)convertToTimeString
{
    if (self.length <10)
    {
        return nil;
    }
    long long thisTimestamp = [[self substringToIndex:10] longLongValue];
    
    long long curTimestamp = [[NSDate date] timeIntervalSince1970];
    NSUInteger seconds= [[NSTimeZone systemTimeZone] secondsFromGMTForDate:[NSDate date]];
    long long todayTimestamp = curTimestamp - (curTimestamp % ONE_DATE_TIME) - seconds;
    long long dTimestamp = todayTimestamp - thisTimestamp;
    if (dTimestamp > TWO_DATE_TIME) {
        // 三天前, 使用: yyyy-MM-dd HH:mm
        return [NSString timestampConvertString:thisTimestamp dataFormat:@"yyyy-MM-dd HH:mm"];
    } else if (dTimestamp > ONE_DATE_TIME) {
        // 两天前, 使用: 前天 HH:mm
        NSString *timeStr = [NSString timestampConvertString:thisTimestamp dataFormat:@"HH:mm"];
        return [NSString stringWithFormat:@"前天 %@", timeStr];
    } else if (dTimestamp > 0) {
        // 一天前, 使用: 昨天 HH:mm
        NSString *timeStr = [NSString timestampConvertString:thisTimestamp dataFormat:@"HH:mm"];
        return [NSString stringWithFormat:@"昨天 %@", timeStr];
    } else if (thisTimestamp < todayTimestamp + ONE_DATE_TIME) {
        NSString *timeStr = [NSString timestampConvertString:thisTimestamp dataFormat:@"HH:mm"];
        return [NSString stringWithFormat:@"今天 %@", timeStr];
    } else {
        // 今天以后, 使用: yyyy-MM-dd HH:mm
        return [NSString timestampConvertString:thisTimestamp dataFormat:@"yyyy-MM-dd HH:mm"];
    }
    return nil;
}

// 转为 发布 4-14 12:00
- (NSString *)convertTimeString
{
    if (self.length <10)
    {
        return nil;
    }
    long long thisTimestamp = [[self substringToIndex:10] longLongValue];
    return [NSString timestampConvertString:thisTimestamp dataFormat:@"MM/dd HH:mm"];
    
}

- (NSString *)compareWihtTime:(NSString *)curTime;
{
    if (self.length <10)
    {
        return nil;
    }
    long long thisTimestamp = [[self substringToIndex:10] longLongValue];
    long long curTimestamp = [[curTime substringToIndex:10] longLongValue];
    
    long long dTime = curTimestamp - thisTimestamp;
    
    if (dTime < 60) {
        return @"刚刚";
    }
    
    if (dTime < 60 * 60) {
        return [NSString stringWithFormat:@"%lld分钟前", dTime / 60];
    }
    
    if (dTime < 60 * 60 * 24) {
        return [NSString stringWithFormat:@"%lld小时前", dTime / (60 * 60)];
    }
    
    return [NSString timestampConvertString:thisTimestamp dataFormat:@"MM月dd日 HH:mm"];
}

+ (NSString *)generateUniqueId
{
    CFUUIDRef   uuid;
    CFStringRef uuidStr;
    
    uuid = CFUUIDCreate(NULL);
    assert(uuid != NULL);
    
    uuidStr = CFUUIDCreateString(NULL, uuid);
    assert(uuidStr != NULL);
    
    CFRelease(uuid);
    
    return (NSString *)CFBridgingRelease(uuidStr);
}

+ (NSString *)getDocumentLocation
{
    if (locDocumentPath == nil) {
        NSArray  *documentPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
        if(documentPaths.count > 0)
        {
            locDocumentPath = [documentPaths objectAtIndex:0];
        }
    }
    
    return locDocumentPath;
}

+ (NSString *)getTempLocation
{
    if (locTempPath == nil) {
        NSError * error;
        NSString * docpath = nil;
        NSArray  *documentPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
        if(documentPaths.count > 0)
        {
            docpath = [documentPaths objectAtIndex:0];
            if(docpath)
            {
                docpath = [docpath stringByAppendingPathComponent:TEMP_FOLDER_NAME];
                if(![[NSFileManager defaultManager] fileExistsAtPath:docpath])
                {
                    [[NSFileManager defaultManager] createDirectoryAtPath:docpath withIntermediateDirectories:YES attributes:nil error:&error];
                    if(error!=nil)
                    {
                        return nil; // Cannot create a directory
                    }
                }
                locTempPath = docpath;
            }
        }
    }
    return locTempPath;
}

+ (NSString *)getImageLocation
{
    if (locImagePath == nil) {
        NSError * error;
        NSString * docpath = nil;
        NSArray  *documentPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
        if(documentPaths.count > 0)
        {
            docpath = [documentPaths objectAtIndex:0];
            if(docpath)
            {
                docpath = [docpath stringByAppendingPathComponent:IMAGE_FOLDER_NAME];
                if(![[NSFileManager defaultManager] fileExistsAtPath:docpath])
                {
                    [[NSFileManager defaultManager] createDirectoryAtPath:docpath withIntermediateDirectories:YES attributes:nil error:&error];
                    if(error!=nil)
                    {
                        return nil; // Cannot create a directory
                    }
                }
                locImagePath = docpath;
            }
        }
    }
    return locImagePath;
}

+ (NSString *)getAvatarLocation
{
    if (locAvatarPath == nil) {
        NSError * error;
        NSString * docpath = nil;
        NSArray  *documentPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
        if(documentPaths.count > 0)
        {
            docpath = [documentPaths objectAtIndex:0];
            if(docpath)
            {
                docpath = [docpath stringByAppendingPathComponent:kAvatarDir];
                if(![[NSFileManager defaultManager] fileExistsAtPath:docpath])
                {
                    [[NSFileManager defaultManager] createDirectoryAtPath:docpath withIntermediateDirectories:YES attributes:nil error:&error];
                    if(error!=nil)
                    {
                        return nil; // Cannot create a directory
                    }
                }
                locAvatarPath = docpath;
            }
        }
    }
    return locAvatarPath;
}


+ (NSString *)getAudioLocation
{
    if (locAudioPath == nil) {
        NSError * error;
        NSString * docpath = nil;
        NSArray  *documentPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
        if(documentPaths.count > 0)
        {
            docpath = [documentPaths objectAtIndex:0];
            if(docpath)
            {
                docpath = [docpath stringByAppendingPathComponent:kAudioDir];
                if(![[NSFileManager defaultManager] fileExistsAtPath:docpath])
                {
                    [[NSFileManager defaultManager] createDirectoryAtPath:docpath withIntermediateDirectories:YES attributes:nil error:&error];
                    if(error!=nil)
                    {
                        return nil; // Cannot create a directory
                    }
                }
                locAudioPath = docpath;
            }
        }
    }
    return locAudioPath;
}

+ (NSString*)getLaunchImage
{
    if (launchImagePath == nil) {
        NSError * error;
        NSString * docpath = nil;
        NSArray  *documentPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
        if(documentPaths.count > 0)
        {
            docpath = [documentPaths objectAtIndex:0];
            if(docpath)
            {
                docpath = [docpath stringByAppendingPathComponent:kLaunchImage];
                if(![[NSFileManager defaultManager] fileExistsAtPath:docpath])
                {
                    [[NSFileManager defaultManager] createDirectoryAtPath:docpath withIntermediateDirectories:YES attributes:nil error:&error];
                    if(error!=nil)
                    {
                        return nil; // Cannot create a directory
                    }
                }
                launchImagePath = docpath;
            }
        }
    }
    return launchImagePath;
}

// 时间戳为毫秒
+ (NSString *)timestampConvertString:(long long)time {

    NSString *timeStr = [NSString timestampConvertString:time dataFormat:@"HH:mm"];
    
    return timeStr;
}

+ (NSString *)timestampConvertString:(long long)time dataFormat:(NSString *)dataFormat
{
    NSString *myStr = [NSString stringWithFormat:@"%lld", time];
    
    // 至少10位
    if (myStr.length < 10) {
        return nil;
    }
    
    NSString *myStr_s = [myStr substringToIndex:10];
    //LogInfo(@"...%@...", myStr_s);
    
    NSDate *date = [NSDate dateWithTimeIntervalSince1970:[myStr_s longLongValue]];
    //LogInfo(@"date:%@", [date description]);
    
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateStyle:NSDateFormatterMediumStyle];
    [formatter setTimeStyle:NSDateFormatterShortStyle];
    //[formatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    //[formatter setDateFormat:@"yyyy-MM-dd HH:mm"];
    [formatter setDateFormat:dataFormat];
    
    NSString *timeStr = [formatter stringFromDate:date];
    //LogInfo(@"timeStr:%@", timeStr);
    
    return timeStr;
}



// 获取半小时后的时间字串
+ (NSString *)halfHourAfterCurrentTime {

//    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
//    [formatter setDateFormat:@"yyyyMMddHHmm"];  // 到分
//    
//    NSDate *date = [NSDate date];
//    NSString *timeStr = [formatter stringFromDate:date];
//    long long timeCount = [timeStr longLongValue];
//    LogInfo(@"current:%lld", timeCount);
//    timeCount += 30;
//    LogInfo(@"halfHour:%lld", timeCount);
    
    NSDate *date = [NSDate date];
    NSDate *nextDate = [date dateByAddingTimeInterval:(30*60)]; // 加半小时
    
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"yyyy-MM-dd HH:mm"];  // 到分
    NSString *timeStr = [formatter stringFromDate:nextDate];
    LogInfo(@"half an hour time string:%@", timeStr);
    return timeStr;
    
}

// 获取24小时后的时间字串
+ (NSString *)oneDayAfterCurrentTime {
    
    NSDate *date = [NSDate date];
    NSDate *nextDate = [date dateByAddingTimeInterval:(24*3600)];   // 加一天
    
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"yyyy-MM-dd HH:mm"];  // 到分
    NSString *timeStr = [formatter stringFromDate:nextDate];
    LogInfo(@"24 hours time string:%@", timeStr);
    return timeStr;
    
}

// 获取24小时前的时间字串
+ (NSString *)oneDayBeforeCurrentTime {

    NSDate *date = [NSDate date];
    NSDate *nextDate = [date dateByAddingTimeInterval:-(24*3600)];   // 减一天
    
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"yyyy-MM-dd HH:mm"];  // 到分
    NSString *timeStr = [formatter stringFromDate:nextDate];
    LogInfo(@"24 hours time string:%@", timeStr);
    return timeStr;
    
}

+ (NSString *)isFullUrl:(NSString *)urlStr
{
    NSString *url = [urlStr stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]] ;
    if (url.length==0)
    {
        return url;
    }
    if ([[url substringToIndex:1] isEqualToString:@"/"])
    {
        NSMutableString* fullUrl = [NSMutableString stringWithString:THE_SOURCE_URL];
        [fullUrl appendFormat:@"%@",url];
        return fullUrl;
    }else
    {
        return url;
    }
}

+ (NSString*)URLencode:(NSString *)originalString
        stringEncoding:(NSStringEncoding)stringEncoding {
    
    NSArray *escapeChars = [NSArray arrayWithObjects:@";" , @"/" , @"?" , @":" ,
                            @"@" , @"&" , @"=" , @"+" ,    @"$" , @"," ,
                            @"!", @"'", @"(", @")", @"*", nil];
    
    NSArray *replaceChars = [NSArray arrayWithObjects:@"%3B" , @"/", @"?" , @":" ,
                             @"%40" , @"&" , @"=" , @"%2B" , @"%24" , @"%2C" ,
                             @"%21", @"%27", @"%28", @"%29", @"%2A", nil];
    
    int len = [escapeChars count];
    
    NSMutableString *temp = [[originalString
                              stringByAddingPercentEscapesUsingEncoding:stringEncoding]
                             mutableCopy];
    
    int i;
    for (i = 0; i < len; i++) {
        
        [temp replaceOccurrencesOfString:[escapeChars objectAtIndex:i]
                              withString:[replaceChars objectAtIndex:i]
                                 options:NSLiteralSearch
                                   range:NSMakeRange(0, [temp length])];
    }
    
    NSString *outStr = [NSString stringWithString: temp];
    
    return outStr;
}

- (NSString *)getShortUrl
{
    if (self.length == 0) {
        return @"";
    }
    if (![self hasPrefix:@"http"]) {
        return @"";
    }
    NSString *requestUrl = [NSString stringWithFormat:@"http://api.t.sina.com.cn/short_url/shorten.json?source=%@&url_long=%@", SINA_API_KEY, [self stringByReplacingOccurrencesOfString:@"&" withString:@"%26"]];
    NSData *data = [NSURLConnection sendSynchronousRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:requestUrl]] returningResponse:nil error:nil];
    NSString *urlStr = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
    NSArray *jsonObject = [urlStr objectFromJSONString];
    if ([jsonObject isKindOfClass:[NSArray class]]) {
        NSDictionary *dic = jsonObject[0];
        if ([dic isKindOfClass:[NSDictionary class]]) {
            urlStr = dic[@"url_short"];
            return urlStr;
        }
    }
    return @"";
}

//去掉空格
-(NSString *)trim
{
    return [self stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
}

+ (BOOL)isExistString:(NSString *)srcStr fingStr:(NSString *)destStr
{
    if (destStr.length==0 || srcStr.length==0)
    {
        return NO;
    }
    for (int i=0; i<srcStr.length; i+=destStr.length)
    {
        NSString *subStr = [srcStr substringWithRange:NSMakeRange(i, destStr.length)];
        if ([subStr isEqualToString:destStr])
        {
            return YES;
        }
    }
    return NO;
}


+ (NSString *)prepareImageWithDic:(NSDictionary *)info
{
    NSString * path = [NSString getImageLocation];
    NSString * name = nil;
    NSString * ext = nil;
    NSString * filename = nil;
    UIImage *image = nil;
    NSURL * refURL;
    NSError * error = nil;
    
    
    refURL = [info objectForKey:UIImagePickerControllerReferenceURL];
    if (refURL==nil)
    {
        LogTrace(@"Image from camera");
        name = [NSString generateUniqueId];
        ext = @"jpg";
    }
    else
    {
        LogTrace(@"Image from photo library");
        NSString * q = [refURL query];
        NSArray * pairs = [q componentsSeparatedByString:@"&"];
        for (NSString * pair in pairs)
        {
            NSArray * bits = [pair componentsSeparatedByString:@"="];
            if (bits.count >= 2)
            {
                NSString * key = [[bits objectAtIndex:0] stringByReplacingPercentEscapesUsingEncoding:NSASCIIStringEncoding];
                
                if([key isEqualToString:@"id"])
                {
                    name = [[bits objectAtIndex:1] stringByReplacingPercentEscapesUsingEncoding:NSASCIIStringEncoding];
                }
                else if([key isEqualToString:@"ext"])
                {
                    ext = [[[bits objectAtIndex:1] stringByReplacingPercentEscapesUsingEncoding:NSASCIIStringEncoding] lowercaseString];
                }
            }
        }
    }
    
    filename = [path stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.%@", name, ext]];
    NSFileManager *fileManager = [NSFileManager defaultManager];
    int count = 1;
    while ([fileManager fileExistsAtPath:filename]) {
        filename = [path stringByAppendingPathComponent:[NSString stringWithFormat:@"%@_%d.%@", name, count, ext]];
        count ++;
    }
    
    image = [info objectForKey:UIImagePickerControllerEditedImage];
    if(image == nil)
    {
        image = [info objectForKey:UIImagePickerControllerOriginalImage];
    }
    [UIImageJPEGRepresentation(image, 0.6) writeToFile:filename options:NSAtomicWrite error:&error];
    return filename;
}

@end
